package vashion.azeroth.core.exchangerate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import com.alibaba.fastjson.JSON;

import vashion.azeroth.contant.ExchangeRateConstants;
import vashion.azeroth.core.item.pojo.ExchangeRateAPIResult;
import vashion.azeroth.core.item.pojo.ExchangeRateOfBank;
import vashion.azeroth.core.item.pojo.ExchangeRateOfCurrency;
import vashion.azeroth.core.item.pojo.JuHeExchangeRateAPIResult;
import vashion.azeroth.core.item.pojo.JuHeExchangeRateOfCurrency;

/**
 * @author Loki 2017.01.19 获得实时银行汇率数据
 *
 */
public class ExchangeRateUtils {

	private final static Logger logger = LoggerFactory.getLogger(ExchangeRateUtils.class);
	
	@Autowired
	ExchangeRateConfigure exchangeRateConfigure;

	/**
	 * 使用NowAPI接口获取指定货币的四大银行的汇率
	 * 
	 * @param curno
	 *            货币代码
	 * @return 货币汇率查询结果
	 * @throws Exception
	 */
	public ExchangeRateAPIResult getNowAPIExchangeRate(String curno) throws Exception {

		
		HttpClient httpclient = new DefaultHttpClient();
		// 设置请求参数
		HttpPost httpPost = new HttpPost(exchangeRateConfigure.getNowapiUrl());
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		nvps.add(new BasicNameValuePair("app", exchangeRateConfigure.getNowapiApp()));
		nvps.add(new BasicNameValuePair("curno", curno.toUpperCase()));
		nvps.add(new BasicNameValuePair("appkey", exchangeRateConfigure.getNowapiAppKey()));
		nvps.add(new BasicNameValuePair("sign", exchangeRateConfigure.getNowapiSign()));
		nvps.add(new BasicNameValuePair("format", exchangeRateConfigure.getNowapiFormat()));
		// 发起请求，获取数据
		String rateJason = null;
		try {
			httpPost.setEntity(new UrlEncodedFormEntity(nvps));
			HttpResponse response = httpclient.execute(httpPost);
			HttpEntity entity = response.getEntity();
			rateJason = EntityUtils.toString(entity, "UTF-8");
		} catch (Exception e) {
			logger.error("获取汇率异常", e);
			throw e;
		} finally {
			httpclient.getConnectionManager().shutdown();
		}
		ExchangeRateAPIResult exchangeRateAPIResult = null;
		// 解析Json字符串
		if (StringUtils.isNotEmpty(rateJason)) {
			exchangeRateAPIResult = JSON.parseObject(rateJason, ExchangeRateAPIResult.class);
		}
		return exchangeRateAPIResult;
	}

	/**
	 * 使用JuHe接口获取指定货币的四大银行的汇率
	 * 
	 * @return 货币汇率查询结果
	 * @throws Exception
	 */
	public JuHeExchangeRateAPIResult getJuHeExchangeRate() throws Exception {

		// 获取配置
		HttpClient httpclient = new DefaultHttpClient();
		// 设置请求参数
		HttpPost httpPost = new HttpPost(exchangeRateConfigure.getJuheUrl());
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		nvps.add(new BasicNameValuePair("key", exchangeRateConfigure.getJuheKey()));
		nvps.add(new BasicNameValuePair("type", exchangeRateConfigure.getJuheType()));
		nvps.add(new BasicNameValuePair("bank", exchangeRateConfigure.getJuheBank()));
		// 发起请求，获取数据
		String rateJason = null;
		try {
			httpPost.setEntity(new UrlEncodedFormEntity(nvps));
			HttpResponse response = httpclient.execute(httpPost);
			HttpEntity entity = response.getEntity();
			rateJason = EntityUtils.toString(entity, "UTF-8");
		} catch (Exception e) {
			logger.error("获取汇率异常", e);
			throw e;
		} finally {
			httpclient.getConnectionManager().shutdown();
		}
		JuHeExchangeRateAPIResult exchangeRateAPIResult = null;
		// 解析Json字符串
		if (StringUtils.isNotEmpty(rateJason)) {
			exchangeRateAPIResult = JSON.parseObject(rateJason, JuHeExchangeRateAPIResult.class);
		}
		return exchangeRateAPIResult;
	}

	/**
	 * 获取指定货币的中国银行现汇卖出价
	 * 
	 * @param curno
	 * @return
	 * @throws Exception
	 */
	public double getCnSellOfBOC(String curno) throws Exception {
		double exchageRateOfBOC = 0.0;
		ExchangeRateOfBank exchangeRateOfBank = this.getExchangeRateOfBOC(curno);
		if (null != exchangeRateOfBank) {
			exchageRateOfBOC = exchangeRateOfBank.getCn_sell();
		}
		return exchageRateOfBOC;
	}

	/**
	 * 获取指定货币的中国银行所有价格
	 * 
	 * @param curno
	 * @return
	 * @throws Exception
	 */
	public ExchangeRateOfBank getExchangeRateOfBOC(String curno) throws Exception {
		ExchangeRateOfBank exchangeRateOfBank = null;
		try {
			ExchangeRateAPIResult exchangeRateAPIResult = getNowAPIExchangeRate(curno);
			if (null != exchangeRateAPIResult) {
				if (exchangeRateAPIResult.getSuccess() == 1) {
					exchangeRateOfBank = exchangeRateAPIResult.getResult().get(curno).getBOC();
					return exchangeRateOfBank;
				} else if (exchangeRateAPIResult.getSuccess() != 1) {
					logger.error(exchangeRateAPIResult.getMsg());
				}
			}

			JuHeExchangeRateAPIResult juHeExchangeRateAPIResult = getJuHeExchangeRate();

			if (null != juHeExchangeRateAPIResult) {
				if (juHeExchangeRateAPIResult.getResultcode() == 200
						&& !CollectionUtils.isEmpty(juHeExchangeRateAPIResult.getResult())
						&& !CollectionUtils.isEmpty(juHeExchangeRateAPIResult.getResult().get(0))) {
					exchangeRateOfBank = new ExchangeRateOfBank();
					JuHeExchangeRateOfCurrency juHeExchangeRateOfCurrency = null;
					HashMap<String, JuHeExchangeRateOfCurrency> juHeExchangeRateMap = juHeExchangeRateAPIResult
							.getResult().get(0);
					//获取相应货币的汇率
					if ("USD".equalsIgnoreCase(curno)) {
						juHeExchangeRateOfCurrency = juHeExchangeRateMap.get("美元");
					} else if ("EUR".equalsIgnoreCase(curno)) {
						juHeExchangeRateOfCurrency = juHeExchangeRateMap.get("欧元");
					} else if ("HKD".equalsIgnoreCase(curno)) {
						juHeExchangeRateOfCurrency = juHeExchangeRateMap.get("港币");
					} else if ("JPY".equalsIgnoreCase(curno)) {
						juHeExchangeRateOfCurrency = juHeExchangeRateMap.get("日元");
					} else if ("GBP".equalsIgnoreCase(curno)) {
						juHeExchangeRateOfCurrency = juHeExchangeRateMap.get("英镑");
					} else if ("TWD".equalsIgnoreCase(curno)) {
						juHeExchangeRateOfCurrency = juHeExchangeRateMap.get("新台币");
					} else if ("KRW".equalsIgnoreCase(curno)) {
						juHeExchangeRateOfCurrency = juHeExchangeRateMap.get("韩国元");
					} else if ("CNY".equalsIgnoreCase(curno)) {
						juHeExchangeRateOfCurrency = new JuHeExchangeRateOfCurrency();
						juHeExchangeRateOfCurrency.setFBuyPri(100D);
						juHeExchangeRateOfCurrency.setFSellPri(100D);
						juHeExchangeRateOfCurrency.setMBuyPri(100D);
						juHeExchangeRateOfCurrency.setMSellPri(100D);
						juHeExchangeRateOfCurrency.setBankConversionPri(100D);
					}
					//转化成统一格式
					exchangeRateOfBank.setBankno("BOC");
					exchangeRateOfBank.setBanknm("中国银行");
					exchangeRateOfBank.setUpddate(juHeExchangeRateOfCurrency.getUpdateDate());
					exchangeRateOfBank.setSe_buy(juHeExchangeRateOfCurrency.getFBuyPri());
					exchangeRateOfBank.setSe_sell(juHeExchangeRateOfCurrency.getFSellPri());
					exchangeRateOfBank.setCn_buy(juHeExchangeRateOfCurrency.getMBuyPri());
					exchangeRateOfBank.setCn_sell(juHeExchangeRateOfCurrency.getMSellPri());
					exchangeRateOfBank.setMiddle(juHeExchangeRateOfCurrency.getBankConversionPri());
					return exchangeRateOfBank;
				} else if (juHeExchangeRateAPIResult.getResultcode() != 200) {
					logger.error(juHeExchangeRateAPIResult.getReason());
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return exchangeRateOfBank;
	}

	/**
	 * 获取指定货币的配置文件中设置的银行的现汇卖出价
	 * 
	 * @param curno
	 * @return
	 * @throws Exception
	 */
	public double getCnSellOfConfigBank(String curno) throws Exception {
		double exchageRateOfBOC = 0.0;
		ExchangeRateAPIResult exchangeRateAPIResult = getNowAPIExchangeRate(curno);
		if (null != exchangeRateAPIResult && exchangeRateAPIResult.getSuccess() == 1) {
			ExchangeRateOfCurrency exchangeRate = exchangeRateAPIResult.getResult().get(curno);
			if (ExchangeRateConstants.BankNos.ABC.equalsIgnoreCase(exchangeRateConfigure.getNowapiBankNo())) {
				exchageRateOfBOC = exchangeRate.getABC().getCn_sell();
			} else if (ExchangeRateConstants.BankNos.CCB.equalsIgnoreCase(exchangeRateConfigure.getNowapiBankNo())) {
				exchageRateOfBOC = exchangeRate.getCCB().getCn_sell();
			} else if (ExchangeRateConstants.BankNos.CEB.equalsIgnoreCase(exchangeRateConfigure.getNowapiBankNo())) {
				exchageRateOfBOC = exchangeRate.getCEB().getCn_sell();
			} else if (ExchangeRateConstants.BankNos.ICBC.equalsIgnoreCase(exchangeRateConfigure.getNowapiBankNo())) {
				exchageRateOfBOC = exchangeRate.getICBC().getCn_sell();
			} else {
				exchageRateOfBOC = exchangeRate.getBOC().getCn_sell();
			}
		}
		return exchageRateOfBOC;
	}

}
